/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-07-02
 * Time: 10:26
 */
class Solution24 {
    int[] dx = {0,0,1,-1,1,1,-1,-1};
    int[] dy = {1,-1,0,0,-1,1,-1,1};
    int m,n;

    public char[][] updateBoard(char[][] board, int[] click) {
        m = board.length;
        n = board[0].length;
        int x = click[0],y = click[1];

        //1.先来进行判断，如果点击的就是地雷，游戏结束
        if(board[x][y] == 'M') {
            board[x][y] = 'X';
            return board;
        }
        //2.此时说明点击的是空方块
        dfs(board,x,y);
        return board;
    }

    void dfs(char[][] board,int i,int j) {
        //1.周围有地雷，改成地雷个数,统计地雷个数
        //2.无地雷，改成 B 空方格
        int count = 0;

        //先统计个数
        for(int k = 0; k < 8; k++) {
            int x = i+dx[k],y = j+dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') {
                count++;
            }
        }
        //周围没有地雷
        if(count == 0) {
            board[i][j] = 'B';
            //根据题意，没有相邻的地雷快，修改为B，还需要和所有相邻的未挖出方块递归地揭露！！
            for(int k = 0; k < 8; k++) {
                int x = i+dx[k],y = j+dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') {
                    dfs(board,x,y);
                }
            }
            //周围有地雷
        }else {
            board[i][j] = (char)('0'+count);
            return;
        }
    }
}